// menu 格式化为 route 格式
function routeFormat(menu) {
  return {
    name: menu.menu_name,
    path: menu.route_path,
    component: menu.component,
    meta: {
      title: menu.menu_name,
      i18nKey: menu.i18n_key,
      constant: menu.constant,
      hideInMenu: menu.hide_in_menu,
      keepAlive: menu.keep_alive,
      icon: menu.icon,
      order: menu.sequence ? menu.sequence : 0,
      href: menu.href,
      activeMenu: menu.active_menu,
      multiTab: menu.multi_tab
    }
  }
}

function menuFormat(menu) {
  return {
    id: menu.id,
    menuType: menu.menu_type,
    menuName: menu.menu_name,
    iconType: menu.icon_type,
    icon: menu.icon,
    routeName: menu.route_name,
    routePath: menu.route_path,
    component: menu.component,
    pathParam: menu.path_param,
    status: menu.status,
    activeMenu: menu.active_menu,
    hideInMenu: menu.hide_in_menu,
    pid: menu.pid,
    sequence: menu.sequence,
    i18nKey: menu.i18n_key,
    keepAlive: menu.keep_alive,
    constant: menu.constant,
    href: menu.href,
    multiTab: menu.multi_tab,
    createdAt: menu.created_at,
    createdBy: menu.created_by,
    updatedAt: menu.updated_at,
    updatedBy: menu.updated_by
  }
}

// 递归构建菜单树
function buildMenuTree(menus = [], pid = 0) {
  const menuMap = new Map()

  menus.forEach((menu) => {
    const list = menuMap.get(menu.pid) || []
    list.push(menu)
    menuMap.set(menu.pid, list)
  })

  const children = menuMap.get(pid) || []

  children.sort((a, b) => a.sequence - b.sequence)

  return children.map((menu) => ({
    ...routeFormat(menu),
    children: buildMenuTree(menus, menu.id)
  }))
}

function buildTree(items, parentIdField = 'pid', idField = 'id', orderField = 'sequence') {
  const itemMap = new Map()

  items.forEach((item) => {
    const node = { ...item, children: [] }
    const parentId = String(item[parentIdField])

    if (!itemMap.has(parentId)) {
      itemMap.set(parentId, [])
    }
    itemMap.get(parentId).push(menuFormat(node))
  })

  if (orderField) {
    itemMap.forEach((children) => {
      children.sort((a, b) => {
        return Number(a[orderField]) - Number(b[orderField])
      })
    })
  }

  function buildSubTree(parentId) {
    const children = itemMap.get(parentId) || []
    children.forEach((child) => {
      child.children = buildSubTree(String(child[idField]))
      if (!child.children.length) {
        delete child.children
      }
    })
    return children
  }

  return buildSubTree('0')
}

module.exports = {
  routeFormat,
  buildMenuTree,
  buildTree
}
